package org.hoyi.web.ctrls;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.hoyi.DB.ctrl.Console;
import org.hoyi.dishop.HoyiModPage;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.dispatchs.responseUtil;
import org.hoyi.disptachs.model.JsonModel;
import org.hoyi.util.CutStrInfo;

/**
 * 
 * HTML模块化控件， 主要属性: id="", id src="", html源路径 datasource="",
 * 数据源,pgcount,datacount,curindx, data:{}, 内容是循环获取.
 * 
 * 
 * @author sam
 *
 */
public class Module extends IHoyiCtrl {
	/**
	 * 读取到的所有类.
	 */
	public Map<String, String> attributes = new HashMap<String, String>();

	public Module(String ctrid) {
		super(ctrid);
	}

	public Module(String ctrid, IHoyiCtrl parent) {
		super(ctrid, parent);
	}

	public String getId() {
		return super.getId();
	}

	public void setId(String id) {
		super.setId(id);
	}

	public String Render() {
		return RenderT(this.HtmlContent);
	}
	
	public static String StartTag = "<Module ";
	public static String EndTag = "</Module>";
	
	/**
	 * 从HTML内获取Module块，并渲染出来.
	 * @param HTMLContent
	 * @return
	 */
	public static String RenderModule(Hoyipage rootpg, String HTMLContent){
		try {
			int modid = 0;
			HTMLContent = HTMLContent.replace("<%#", "--HOYILEFT%#--");
			HTMLContent = HTMLContent.replace("#%>", "--#%HOYIRIGHT--");
			while (CanCut(HTMLContent)) {
				modid ++;
				CutStrInfo strInfo = new CutStrInfo(StartTag, EndTag);
			    boolean contain = strInfo.Calc(HTMLContent);
			    if (contain) {
			    	String modulecontent = strInfo.getEXPREDContent();

			    	Document document = DocumentHelper.parseText(modulecontent);
			    	Attribute srcattr = document.getRootElement().attribute("src");
			    	Attribute typeattr = document.getRootElement().attribute("type");
			    	
			    	if(srcattr != null) {// 获取到SRC
			    		String src = srcattr.getValue();
			    		String moduleHTML = rootpg.WRITEHTML(src);
			    		HTMLContent = HTMLContent.replace(modulecontent, moduleHTML);
			    		
			    		List<Attribute> attrs = document.getRootElement().attributes();
			    		for (Attribute attribute : attrs) {
			    			if(!attribute.getName().toLowerCase().equals("src")) {
			    				HTMLContent = HTMLContent.replace("{{ " + attribute.getName() + " }}", attribute.getValue());
			    				HTMLContent = HTMLContent.replace("{{" + attribute.getName() + "}}", attribute.getValue());
			    			}
						}
			    	}else if(typeattr !=  null) {
			    		// 如果有type.则用hoyimp初始化渲染后，返回内容.
			    		String _requrl = typeattr.getValue();
//			    		String _requrl = "/modules/sub1";
			    		_requrl = _requrl.replace("/", ".");
			    		Class disp = null;
			    		String reqclass = "WebRoot" + _requrl;
			    		try {
			    			disp = Thread.currentThread().getContextClassLoader().loadClass(reqclass);
			    			
			    			Constructor[] cons = disp.getConstructors();
			    			HoyiModPage mpage = (HoyiModPage) cons[0].newInstance(new Object[0]);
				    		mpage.InitAndLoadRequestType();
							// 如果验证能通过.
				    		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<UUID:"+ modid);
				    		
				    		mpage.setRequest(rootpg.getRequest());
				    		mpage.setResponse(rootpg.getResponse());
				    		mpage.setuid(modid + "");
				    		mpage.OnPreInit();
				    		String htmls = mpage.getHtmlContent();
				    		System.out.println("_requrl:" + _requrl);
				    		System.out.println(htmls);
				    		HTMLContent = HTMLContent.replace(modulecontent, htmls);
				    		
				    		List<Attribute> attrs = document.getRootElement().attributes();
				    		for (Attribute attribute : attrs) {
				    			if(!attribute.getName().toLowerCase().equals("src")) {
				    				HTMLContent = HTMLContent.replace("{{ " + attribute.getName() + " }}", attribute.getValue());
				    				HTMLContent = HTMLContent.replace("{{" + attribute.getName() + "}}", attribute.getValue());
				    			}
							}
			    		}catch (Exception e) {
			    			HTMLContent = HTMLContent.replace(modulecontent, "<p>Module Content Rend ModPg Error,Check Pls!~.</p>");
						}
			    	}else {
			    		HTMLContent = HTMLContent.replace(modulecontent, "<p>Module Content Errored,Check Pls!~.</p>");
			    	}
			    }

			}
    		HTMLContent = HTMLContent.replace("--HOYILEFT%#--", "<%#");
    		HTMLContent = HTMLContent.replace("--#%HOYIRIGHT--", "#%>");
			// 这里把{{ }} {{}} 这种全部清掉，因为是多余的Tag.
			while (CanCutDataTag(HTMLContent)) {
				CutStrInfo strInfo = new CutStrInfo("{{", "}}");
				 boolean contain = strInfo.Calc(HTMLContent);
				 if(contain) {
					 HTMLContent = HTMLContent.replace(strInfo.getEXPREDContent(), "");
				 }
			}
		} catch (Exception e) {
			Console.Error("Module Render Error:" + e.getMessage());
		}
		
		return HTMLContent;
	}
	/**
	 * 是否存在，Module。
	 * @param Htmls
	 * @return
	 */
	public static boolean CanCut(String Htmls) {
		try {
			if(Htmls.toLowerCase().contains(StartTag.toLowerCase()) && Htmls.toLowerCase().contains(EndTag.toLowerCase())) {
				if(Htmls.toLowerCase().indexOf(StartTag.toLowerCase()) >= 0 &&  Htmls.toLowerCase().indexOf(EndTag.toLowerCase()) > 0) {
					return true;	
				}
			} 
		} catch (Exception e) {
			
		}
		return false;
	}
	/**
	 * 渲染完之后将{{ }} {{}} 这种无数据源的标签全部清除。
	 * @param Htmls
	 * @return
	 */
	public static boolean CanCutDataTag(String Htmls) {
		try {
			if(Htmls.toLowerCase().contains("{{") && Htmls.toLowerCase().contains("}}")) {
				if(Htmls.toLowerCase().indexOf("{{") >= 0 &&  Htmls.toLowerCase().indexOf("}}") > 0) {
					return true;	
				}
			} 
		} catch (Exception e) {
			
		}
		return false;
	}
	
}
